<template>
  <div class="container2">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="nav-back" @click="$router.go(-1)">
        <i class="fas fa-chevron-left"></i>
      </div>
      <div class="nav-title">数据看板</div>
      <div></div>
    </div>

    <!-- 顶部统计区域 -->
    <div class="header">
      <div class="header-content">
        <div class="header-left">
          <h1>员工心理健康监测系统</h1>
          <p>基于员工自评数据的全面分析与跟进管理</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <div class="stat-value">{{ topData.total || 0 }}</div>
            <div class="stat-label">参与员工</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ topData.risk || 0 }}</div>
            <div class="stat-label">高风险员工</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ riskCallBackNo }}%</div>
            <div class="stat-label">风险回拨率</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="dashboard">
      <div class="chart-card">
        <div class="card-header">
          <div class="card-icon">
            <i class="fas fa-venus-mars"></i>
          </div>
          <div class="card-title">员工性别分布</div>
        </div>
        <div class="chart-container">
          <canvas ref="genderChart"></canvas>
        </div>
        <!-- 性别分布数据表格 -->
        <div class="data-table">
          <div class="data-row header">
            <div class="data-cell">性别</div>
            <div class="data-cell">人数</div>
            <div class="data-cell">比例</div>
          </div>
          <div class="data-row" v-for="item in sexDistribution" :key="item.sex">
            <div class="data-cell">{{ item.sex }}</div>
            <div class="data-cell">{{ item.number }}人</div>
            <div class="data-cell">
              {{ calculatePercentage(item.number, totalEmployees) }}%
            </div>
          </div>
        </div>
      </div>
      <br />

      <div class="chart-card">
        <div class="card-header">
          <div class="card-icon">
            <i class="fas fa-user-friends"></i>
          </div>
          <div class="card-title">员工年龄分布</div>
        </div>
        <div class="chart-container">
          <canvas ref="ageChart"></canvas>
        </div>
        <!-- 年龄分布数据表格 -->
        <div class="data-table">
          <div class="data-row header">
            <div class="data-cell">年龄段</div>
            <div class="data-cell">人数</div>
            <div class="data-cell">比例</div>
          </div>
          <div
            class="data-row age-row"
            v-for="item in ageDistribution"
            :key="item.age"
            :class="getAgeClass(item.age)"
          >
            <div class="data-cell">{{ item.age }}</div>
            <div class="data-cell">{{ item.number }}人</div>
            <div class="data-cell">
              {{ calculatePercentage(item.number, totalEmployees) }}%
            </div>
          </div>
        </div>
      </div>
      <br />

      <div class="chart-card">
        <div class="card-header">
          <div class="card-icon">
            <i class="fas fa-shield-alt"></i>
          </div>
          <div class="card-title">风险等级分布</div>
        </div>
        <div class="chart-container">
          <canvas ref="riskChart"></canvas>
        </div>
        <!-- 风险等级分布数据表格 -->
        <div class="data-table">
          <div class="data-row header">
            <div class="data-cell">风险等级</div>
            <div class="data-cell">人数</div>
            <div class="data-cell">比例</div>
          </div>
          <div
            class="data-row"
            v-for="item in riskDistribution"
            :key="item.Prop1"
          >
            <div class="data-cell">{{ item.Prop1 }}风险</div>
            <div class="data-cell">{{ item.number }}人</div>
            <div class="data-cell">
              {{ calculatePercentage(item.number, totalEmployees) }}%
            </div>
          </div>
        </div>
      </div>
    </div>
    <br />

    <!-- 高风险员工跟进区域 -->
    <div class="tracking-section">
      <div class="section-header">
        <div>
          <div class="section-title">高风险员工跟进动态</div>
          <p class="section-subtitle">实时跟踪高风险员工的心理健康干预进展</p>
        </div>
      </div>

      <div class="timeline">
        <!-- 跟进项目 -->
        <div
          class="timeline-item"
          v-for="(item, index) in timelineItems"
          :key="index"
        >
          <div class="timeline-icon">
            <i class="fas fa-user-md"></i>
          </div>
          <div class="timeline-content">
            <div class="timeline-header">
              <div class="employee-info">
                <div class="employee-avatar">{{ item.avatarText }}</div>
                <div>
                  <div class="employee-name">{{ item.name }}</div>
                  <div class="employee-department">{{ item.department }}</div>
                </div>
              </div>
            </div>
            <div class="timeline-status">{{ item.status }}</div>
            <div class="timeline-meta">
              <div
                class="meta-item"
                v-for="(meta, metaIndex) in item.meta"
                :key="metaIndex"
              >
                <i :class="meta.icon"></i> {{ meta.text }}
              </div>
            </div>
            <div class="consultant-info">
              <div class="consultant-avatar">
                {{ item.consultant.avatarText }}
              </div>
              <div class="consultant-name">{{ item.consultant.name }}</div>
            </div>
            <button class="feedback-btn" @click="viewReport()">
              <i class="fas fa-comment-dots"></i> 查看反馈报告
            </button>
          </div>
        </div>
        <div class="btns">
          <button class="retry-btn2" @click="gohome()">返回首页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Chart } from "chart.js/auto";
import { dataBord } from "../../api/manager";

export default {
  name: "EmployeeMentalHealthDashboard",
  data() {
    return {
      riskCallBackNo: 0,
      sexDistribution: [],
      ageDistribution: [],
      topData: {
        total: 0,
        risk: 0,
      },
      riskCallBackInfo: {
        callNo: 0,
      },
      riskDistribution: [],
      consultantList: [],
      timelineItems: [],
      genderChart: null,
      ageChart: null,
      riskChart: null,
      report_url: null,
      timeLength: 0,
      count: 0,
    };
  },
  computed: {
    totalEmployees() {
      return this.topData.total || 0;
    },
  },
  mounted() {
    this.dataBord();
  },
  beforeDestroy() {
    if (this.genderChart) {
      this.genderChart.destroy();
    }
    if (this.ageChart) {
      this.ageChart.destroy();
    }
    if (this.riskChart) {
      this.riskChart.destroy();
    }
  },
  methods: {
    dataBord() {
      let data = {
        unitId: localStorage.getItem("unitId"),
      };
      dataBord(data)
        .then((res) => {
          if (res.code === 200) {
            const data = res.data;
            console.log("接口返回数据:", data);

            // 直接使用接口返回的数据
            this.riskCallBackNo = data.riskCallBackNo || 0;
            this.sexDistribution = data.sexDistribution || [];
            this.ageDistribution = data.ageDistribution || [];
            this.topData = data.topData || { total: 0, risk: 0 };
            this.riskCallBackInfo = data.riskCallBackInfo || { callNo: 0 };
            this.riskDistribution = data.riskDistribution || [];
            this.consultantList = data.consultantList || [];
            this.timeLength = data.timeLength || 0;
            this.count = data.count || 0;

            // 处理 reportUrl
            if (data.reportUrl) {
              this.report_url = data.reportUrl.report_url;
            } else {
              this.report_url = null;
            }

            console.log("处理后的数据:", {
              riskCallBackNo: this.riskCallBackNo,
              sexDistribution: this.sexDistribution,
              ageDistribution: this.ageDistribution,
              topData: this.topData,
              riskDistribution: this.riskDistribution,
              report_url: this.report_url,
            });

            // 更新跟进动态数据
            this.updateTimelineItems();

            this.$nextTick(() => {
              this.initCharts();
            });
          }
        })
        .catch((error) => {
          console.error("获取数据看板失败:", error);
        });
    },
    gohome() {
      this.$router.go(-1);
    },
    updateTimelineItems() {
      let consultantNames = "暂无咨询师";
      if (this.consultantList && this.consultantList.length > 0) {
        consultantNames = this.consultantList
          .map((item) => item.consultantname)
          .join("、");
      }

      this.timelineItems = [
        {
          avatarText: "全员",
          name: "心理健康测评",
          department: `${this.topData.total || 0}人`,
          date: new Date().toISOString().split("T")[0],
          status: "咨询师呼出跟进中",
          meta: [
            {
              icon: "fas fa-phone",
              text: `已通话${this.count || "0"}次`,
            },
            {
              icon: "fas fa-clock",
              text: `累计${this.timeLength || "0"}分钟`,
            },
          ],
          consultant: {
            avatarText: "咨询",
            name: `${consultantNames}${
              this.consultantList && this.consultantList.length > 0
                ? "等心理咨询师"
                : ""
            }`,
          },
        },
      ];
    },
    calculatePercentage(partial, total) {
      if (!total || total === 0) return 0;
      return ((partial / total) * 100).toFixed(2);
    },
    getAgeClass(age) {
      const ageClassMap = {
        "18-25岁": "age-18-25",
        "26-32岁": "age-26-32",
        "33-40岁": "age-33-40",
        其他: "age-other",
      };
      return ageClassMap[age] || "";
    },
    viewReport() {
      if (!this.report_url) {
        alert("暂无反馈报告");
        return;
      }
      this.$router.push({
        name: "反馈报告",
        query: {
          report_url: this.report_url,
        },
      });
    },
    initCharts() {
      // 销毁旧图表
      if (this.genderChart) {
        this.genderChart.destroy();
      }
      if (this.ageChart) {
        this.ageChart.destroy();
      }
      if (this.riskChart) {
        this.riskChart.destroy();
      }

      // 性别分布图表
      const genderCtx = this.$refs.genderChart?.getContext("2d");
      if (genderCtx) {
        const maleData =
          this.sexDistribution.find((item) => item.sex === "男性")?.number || 0;
        const femaleData =
          this.sexDistribution.find((item) => item.sex === "女性")?.number || 0;

        this.genderChart = new Chart(genderCtx, {
          type: "doughnut",
          data: {
            labels: ["男性", "女性"],
            datasets: [
              {
                data: [maleData, femaleData],
                backgroundColor: ["#3b82f6", "#8b5cf6"],
                borderWidth: 0,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: "bottom",
                labels: {
                  padding: 20,
                  font: {
                    size: 13,
                  },
                },
              },
              tooltip: {
                callbacks: {
                  label: (context) => {
                    const total = context.dataset.data.reduce(
                      (a, b) => a + b,
                      0
                    );
                    const percentage =
                      total > 0
                        ? ((context.parsed / total) * 100).toFixed(1)
                        : 0;
                    return `${context.label}: ${context.parsed}人 (${percentage}%)`;
                  },
                },
              },
            },
            cutout: "65%",
          },
        });
      }

      // 年龄分布图表
      const ageCtx = this.$refs.ageChart?.getContext("2d");
      if (ageCtx) {
        const ageLabels = this.ageDistribution.map((item) => item.age);
        const ageData = this.ageDistribution.map((item) => item.number);

        const ageColors = [
          "rgba(59, 130, 246, 0.8)",
          "rgba(139, 92, 246, 0.8)",
          "rgba(16, 185, 129, 0.8)",
          "rgba(245, 158, 11, 0.8)",
        ];

        this.ageChart = new Chart(ageCtx, {
          type: "bar",
          data: {
            labels: ageLabels,
            datasets: [
              {
                label: "员工数量",
                data: ageData,
                backgroundColor: ageColors,
                borderColor: [
                  "rgb(59, 130, 246)",
                  "rgb(139, 92, 246)",
                  "rgb(16, 185, 129)",
                  "rgb(245, 158, 11)",
                ],
                borderWidth: 2,
                borderRadius: 6,
                borderSkipped: false,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
              y: {
                beginAtZero: true,
                grid: {
                  drawBorder: false,
                },
                ticks: {
                  precision: 0,
                },
              },
              x: {
                grid: {
                  display: false,
                },
              },
            },
            plugins: {
              legend: {
                display: false,
              },
            },
          },
        });
      }

      // 风险等级分布图表
      const riskCtx = this.$refs.riskChart?.getContext("2d");
      if (riskCtx) {
        const riskLabels = this.riskDistribution.map(
          (item) => item.Prop1 + "风险"
        );
        const riskData = this.riskDistribution.map((item) => item.number);
        const riskColors = {
          高: "#ef4444",
          中: "#f59e0b",
          中低: "#fbbf24",
          低: "#10b981",
        };

        this.riskChart = new Chart(riskCtx, {
          type: "pie",
          data: {
            labels: riskLabels,
            datasets: [
              {
                data: riskData,
                backgroundColor: this.riskDistribution.map(
                  (item) => riskColors[item.Prop1] || "#94a3b8"
                ),
                borderWidth: 0,
              },
            ],
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: "bottom",
                labels: {
                  padding: 20,
                  font: {
                    size: 13,
                  },
                },
              },
              tooltip: {
                callbacks: {
                  label: (context) => {
                    const total = context.dataset.data.reduce(
                      (a, b) => a + b,
                      0
                    );
                    const percentage =
                      total > 0
                        ? ((context.parsed / total) * 100).toFixed(1)
                        : 0;
                    return `${context.label}: ${context.parsed}人 (${percentage}%)`;
                  },
                },
              },
            },
          },
        });
      }
    },
  },
};
</script>

<style scoped>
/* 样式保持不变，与您原来的代码一致 */
.container2 {
  background: linear-gradient(135deg, #f0f4ff 0%, #eef7ff 100%);
  color: #333;
  line-height: 1.6;
  min-height: 100vh;
  padding: 0px 15px 15px 15px;
  max-width: 1200px;
  margin: 0 auto;
}

.navbar {
  top: 0;
  left: 0;
  right: 0;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 50px 0 0px;
  z-index: 1000;
}

.nav-back {
  width: 2.5rem;
  height: 2.5rem;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6366f1;
  border: none;
  cursor: pointer;
}

.nav-back:hover {
  background: #eef0ff;
}

.nav-title {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.header {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border-radius: 18px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3);
  position: relative;
  overflow: hidden;
}

.header::before {
  content: "";
  position: absolute;
  top: -50px;
  right: -30px;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.header-content {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-left h1 {
  font-size: 1.4rem;
  font-weight: 700;
  margin-bottom: 10px;
}

.header-left p {
  font-size: 1rem;
  opacity: 0.9;
}

.header-stats {
  display: flex;
  gap: 25px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.85;
}

.dashboard {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}

.chart-card {
  background: white;
  border-radius: 18px;
  padding: 25px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
}

.card-icon {
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  border-radius: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.2rem;
  margin-right: 15px;
}

.card-title {
  font-size: 1rem;
  font-weight: 600;
  color: #1e293b;
}

.chart-container {
  position: relative;
  height: 250px;
  margin-bottom: 20px;
}

.data-table {
  margin-top: 15px;
  border-radius: 10px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
}

.data-row {
  display: flex;
  padding: 12px 15px;
  border-bottom: 1px solid #e2e8f0;
  background: white;
}

.data-row:last-child {
  border-bottom: none;
}

.data-row.header {
  background: #f8fafc;
  font-weight: 600;
  color: #1e293b;
}

.data-cell {
  flex: 1;
  text-align: center;
  font-size: 0.85rem;
}

.data-cell:first-child {
  text-align: left;
  flex: 1.2;
}

.data-cell:last-child {
  text-align: right;
  flex: 1;
}

.age-row.age-18-25 {
  background: linear-gradient(
    135deg,
    rgba(59, 130, 246, 0.8),
    rgba(59, 130, 246, 0.6)
  );
}
.age-row.age-26-32 {
  background: linear-gradient(
    135deg,
    rgba(139, 92, 246, 0.8),
    rgba(139, 92, 246, 0.6)
  );
}
.age-row.age-33-40 {
  background: linear-gradient(
    135deg,
    rgba(16, 185, 129, 0.8),
    rgba(16, 185, 129, 0.6)
  );
}
.age-row.age-other {
  background: linear-gradient(
    135deg,
    rgba(245, 158, 11, 0.8),
    rgba(245, 158, 11, 0.6)
  );
}

.age-row:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.tracking-section {
  background: white;
  border-radius: 18px;
  padding: 25px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.06);
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 25px;
}

.section-title {
  font-size: 1.2rem;
  font-weight: 700;
  color: #1e293b;
}

.section-subtitle {
  color: #64748b;
  margin-top: 8px;
}

.timeline {
  position: relative;
  padding: 30px 0;
}

.timeline::before {
  content: "";
  position: absolute;
  top: 0;
  bottom: 0;
  left: 30px;
  width: 4px;
  background: #e2e8f0;
  border-radius: 2px;
}

.timeline-item {
  position: relative;
  margin-bottom: 40px;
  padding-left: 80px;
}

.timeline-item:last-child {
  margin-bottom: 0;
}

.timeline-icon {
  position: absolute;
  left: 20px;
  top: 0;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: white;
  border: 3px solid #3b82f6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #3b82f6;
  font-size: 16px;
  z-index: 2;
}

.timeline-content {
  background: #f8fafc;
  border-radius: 14px;
  padding: 20px;
  border-left: 3px solid #3b82f6;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.employee-info {
  display: flex;
  align-items: center;
}

.employee-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  margin-right: 12px;
}

.employee-name {
  font-weight: 600;
  color: #1e293b;
}

.employee-department {
  font-size: 0.8rem;
  color: #64748b;
}

.timeline-status {
  display: inline-block;
  padding: 5px 15px;
  background: #dbeafe;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 500;
  color: #3b82f6;
  margin-bottom: 15px;
}

.timeline-meta {
  display: flex;
  gap: 15px;
  color: #64748b;
  font-size: 0.8rem;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-item i {
  margin-right: 5px;
  color: #94a3b8;
}

.consultant-info {
  display: flex;
  align-items: center;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e2e8f0;
}

.consultant-avatar {
  width: 80px;
  height: 32px;
  border-radius: 25px;
  background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 0.8rem;
  margin-right: 10px;
}

.consultant-name {
  font-weight: 500;
  color: #1e293b;
}

.feedback-btn {
  margin-top: 15px;
  padding: 8px 16px;
  background: #eff6ff;
  border: none;
  border-radius: 6px;
  color: #3b82f6;
  font-weight: 500;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  transition: all 0.3s ease;
}

.feedback-btn i {
  margin-right: 8px;
}

.feedback-btn:hover {
  background: #dbeafe;
}

@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: flex-start;
  }

  .header-stats {
    margin-top: 20px;
    width: 100%;
    justify-content: space-between;
  }

  .timeline-item {
    padding-left: 60px;
  }

  .timeline::before {
    left: 20px;
  }

  .timeline-icon {
    left: 10px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .navbar {
    flex-direction: row;
  }

  .nav-title {
    font-size: 1.1rem;
  }

  .data-cell {
    font-size: 0.8rem;
    padding: 8px 5px;
  }
}

@media (max-width: 480px) {
  .header {
    padding: 20px;
  }

  .stat-value {
    font-size: 1.6rem;
  }

  .chart-card {
    padding: 20px;
  }

  .card-icon {
    width: 40px;
    height: 40px;
    font-size: 1rem;
  }

  .timeline-meta {
    flex-direction: column;
    gap: 8px;
  }

  .nav-title {
    font-size: 1rem;
  }

  .data-table {
    font-size: 0.75rem;
  }
}
.btns {
  display: flex;
  justify-content: space-around;
}
.retry-btn2 {
  background: #40a2f4;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 25px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}
</style>
